package cn.explink.dop.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.explink.dop.entity.vo.AreaVO;
import cn.explink.dop.entity.vo.DeliveryManVO;
import cn.explink.dop.entity.vo.StorefrontVO;
import cn.explink.dop.service.AreaService;
import cn.explink.dop.service.DeliveryManService;
import cn.explink.dop.service.StorefrontService;
import cn.explink.eap.core.common.model.json.AjaxJson;

@Controller
@RequestMapping("/deliveryManRelateController")
public class DeliveryManRelateController {

	@Autowired
	private DeliveryManService deliveryManService;

	@Autowired
	private AreaService areaService;

	@Autowired
	private StorefrontService storefrontService;

	@RequestMapping(params = "index")
	public ModelAndView storefrontIndex(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("dop/deliveryman/deliverymanrelate");
		return view;
	}

	@RequestMapping(params = "assignAreaAndStorefront")
	@ResponseBody
	public AjaxJson assignAreaAndStorefront(String id, @RequestParam(value = "areaIdList[]", required = false) List<String> areaIdList,
			@RequestParam(value = "storefrontIdList[]", required = false) List<String> storefrontIdList, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();

		try {
			// 获取区域
			List<AreaVO> areaVOList = new ArrayList<AreaVO>();
			if (null != areaIdList) {
				for (String areaId : areaIdList) {
					AreaVO areaVO = this.areaService.queryById(areaId);
					areaVOList.add(areaVO);
				}
			}
			// 获取店面
			List<StorefrontVO> storefrontVOList = new ArrayList<StorefrontVO>();
			if (null != storefrontIdList) {
				for (String storefrontId : storefrontIdList) {
					storefrontVOList.add(this.storefrontService.queryById(storefrontId));
				}
			}

			// 获取配送员
			DeliveryManVO deliveryManVO = this.deliveryManService.queryById(id);
			// 分配
			if (areaVOList.size() != 0) {
				deliveryManVO.setAreaList(areaVOList);
			} else {
				deliveryManVO.setAreaList(null);
			}
			if (storefrontVOList.size() != 0) {
				deliveryManVO.setStorefrontList(storefrontVOList);
			} else {
				deliveryManVO.setStorefrontList(null);
			}
			this.deliveryManService.saveOrUpdate(deliveryManVO);
		} catch (Exception e) {
			e.printStackTrace();
		}

		j.setSuccess(true);
		return j;
	}

}
